<template>
  <el-dialog
    title='邮箱有效性验证'
    :close-on-click-modal="false"
    :visible.sync="show"
    :append-to-body="true"
    :height="800"
    :before-close="handleClose"
    top="5vh"
    >
    <el-scrollbar :wrap-class="{wrapClass: true}" class="dialog-scrollbar">
    <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="单一邮箱验证提取" name="first">
      <div>
          <el-tag type="warning">请 注 意 : 邮 箱 有 效 性 验 证 的 准 确 率 取 决 于 对 方 邮 件 服 务 器 反 垃 圾 邮 件 的 安 全 机 制 , 无 法 做 到 1 0 0 % 的 准 确 率 。</el-tag>
      </div>
      <div style="margin-top:15px;">
          <span class="no-padding-input">
              <el-input style="width:2px;">
                  <template slot="prepend">验证进程</template>
              </el-input>
          </span>
          <span class="no-border-radius-input">
              <el-input-number v-model="num" controls-position="right" style="width:90px;"  @change="handleChange" :min="1" :max="10"></el-input-number>
          </span>
          <span>
              <el-input v-model="emailAddressTemp" style="width:50%;margin:0px 20px 0px 20px;" placeholder="请输入待验证的邮箱地址"></el-input>
          </span>
          <span>
                <el-button type="success" @click="handleVerifyEmail">开始验证</el-button>
                <el-button type="danger">取消验证</el-button>
          </span>
      </div>
    </el-tab-pane>
    <el-tab-pane label="批量邮箱验证" name="second">
      <div style="height:220px;">
        <div style="margin-right:20px;">
          <el-tag type="warning">请 在 下 方 输 入 需 要 批 量 验 证 的 邮 箱,一 行 一 个。（如邮箱数量过多,验证时间也会相对长一些）</el-tag>
          <el-button :disabled="validating" size="mini" type="success" style="margin-left:5px;display:inline-block;float:right;" @click="handleVerifyEmails">开始验证</el-button>
          <el-button size="mini" type="primary" style="display:inline-block;float:right;" disabled>上传邮箱</el-button>
        </div>
        <div style="margin-top:10px;">
          <el-input
            type="textarea"
            :autosize="{minRows: 8, maxRows: 9}"
            placeholder="请输入邮箱,一行一个"
            v-model="emailsAddress"
            style="width:900px;">
          </el-input>
        </div>
      </div>
    </el-tab-pane>
    <div style="margin:10px 20px 5px 0px;padding:10px 30px;border:1px solid #DCDFE6;border-radius:5px;">
        <el-checkbox v-model="configList.databaseCheck" disabled>验证前检测数据库</el-checkbox>
        <el-checkbox v-model="configList.saveToDataBase" disabled>自动保存结果</el-checkbox>
    </div>
  </el-tabs>
  <el-tabs v-model="activeNameFirst" @tab-click="handleClickTab">
    <el-tab-pane label="验证结果列表" name="first-first">
      <div style="margin:10px 20px;padding:10px 10px;border:1px solid #e6ebf5;height:72%;">
        <el-table
          :data="emailAddress.filter(data => !searchAddressee || data.email.toLowerCase().includes(searchAddressee.toLowerCase()))"
          style="width: 100%;"
          :height="activeName==='first'?'515px':'375px'"
          >
          <el-table-column label="收件箱" align="center">
            <template slot-scope="scope">
            {{ scope.row.email }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <template v-for="item in stateOptions">
                <template v-if="item['key'] == scope.row.state">
                  <span :class="item.class"><i :class="item.icon"/>{{ item.label }}</span>
                </template>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            align="center">
            <template slot="header" slot-scope="scope">
              <el-input
                v-model="searchAddressee"
                size="mini"
                clearable
                placeholder="输入邮箱搜索"/>
            </template>
            <template slot-scope="scope">
              <!-- <el-button size="mini" plain @click="handleSaveToCustomer(scope.row)" :disabled="scope.row.state!==2">保存为客户</el-button> -->
              <el-button size="mini" plain @click="handleEmailRemove(scope.row)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-tab-pane>
    <el-tab-pane name="first-second">
      <span slot="label">验证日志</span>
      <template>
        <el-table
          :data="verifyLogData"
          style="width: 100%"
          :height="activeName==='first'?'500px':'375px'"
          >
          <el-table-column
            label="序号"
            align="center"
            type="index">
          </el-table-column>
          <el-table-column
            prop="emailAddress"
            label="邮箱"
            align="center"
            min-width="220">
          </el-table-column>
          <el-table-column
            label="有效性"
            align="center"
            min-width="180">
            <template slot-scope="{row}">
              <template v-if="row.state === true ">
                <span class="state_valid">有效</span>
              </template>
              <template v-else>
                <span class="state_invalid">无效</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            min-width="180"
            label="最后更新方式">
            <template slot-scope="{row}">
              <template v-if="row.recentlyUpdatedWay">
                <span>主动</span>
              </template>
              <template v-else>
                <span>被动</span>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </template>
       <pagination
        v-show="listQuery.total>0"
        :total="listQuery.total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getLogList"
        />
    </el-tab-pane>
  </el-tabs>
  <div style="height:15px;">

  </div>
    </el-scrollbar>
  </el-dialog>
</template>
<script>
import { getAction, postAction, getUrlAction, postUrlAction, postLongTimeAction } from '@/api/common'
import Pagination from '@/components/Pagination/index.vue'
export default {
  name: 'VerifyEmail',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Pagination
    // TinymcePage
  },
  data: function() {
    return {
      validating: false,
      listQuery: {
        total: 0,
        page: 1,
        limit: 2
      },
      verifyLogData: [],
      configList: {
        databaseCheck: false,
        saveToDataBase: true
      },
      emailAddressTemp: '',
      emailsAddressTemp: '',
      emailAddress: [],
      emailsAddress: '',
      searchAddressee: '',
      stateOptions: [
        { key: '0', label: '待验证', icon: '<i class="el-icon-success" />' },
        { key: '1', label: '验证中', icon: 'el-icon-loading', class: 'state_verification' },
        { key: '2', label: '有效邮箱', icon: 'el-icon-success', class: 'state_valid' },
        { key: '3', label: '无效邮箱', icon: 'el-icon-error', class: 'state_invalid' },
        { key: '4', label: '已保存', icon: 'el-icon-finished', class: 'state_save' }
      ],
      num: 1,
      sendContentPercentage: 100,
      filterContentPercentage: 50,
      sendSuccessContentPercentage: 80,
      sendFailedContentPercentage: 10,
      activeName: 'first',
      activeNameFirst: 'first-first',
      fileList: [{
        name: 'food.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      }, {
        name: 'food2.jpeg',
        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      }],
      form: {
        Title: '',
        Addresser: '',
        ShowAsEmail: false,
        ReplyEmail: '',
        Addressee: [],
        EmailSubject: '{}',
        TimingTransmission: null
      }
    }
  },
  watch: {
    show(val) {
      this.$emit('update:show', val)
    }
  },
  created() {
    VUE.$on('VerifyEmail', (res) => {
      for (const key in res) {
        const email = this.emailAddress.find(m => m.email === key)
        if (email) {
          email.state = res[key] ? 2 : 3
          this.creatEmailVerify(res[key], key)
        }
      }
      this.emailAddress = [...this.emailAddress]
    })
  },
  destroyed() {
    VUE.$off('VerifyEmail')
    console.log('destroyed')
  },
  methods: {
    handleClick(tab, event) {
      // console.log(tab, event)
    },
    handleChange(value) {
      // console.log(value)
    },
    handleVerifyEmail() {
      // TODO 验证进程满了的时候，默认状态待验证，验证回调检查是否有未完成的进程，直接取代一个，增加手动验证按钮，只有待验证状态可以使用，通过验证中数量来判断进程数
      console.log('开始验证')
      // 验证 邮箱地址是否符合规范
      const emailAddressTemp = this.emailAddressTemp.trim()
      // 验证是否为空
      if (this.emailAddressTemp.length !== 0) {
        // 验证是否邮箱格式
        if (this.checkEmailAddress(emailAddressTemp)) {
          // 验证是否重复
          const result = this.emailAddress.some((item) => {
            if (item.email === emailAddressTemp) {
              return true
            }
            // TODO: 给出选项是否到数据库查询邮箱已经验证过,此处操作查询邮箱是否已经存在
          })
          if (result) {
            this.$message({
              message: '邮箱地址已存在',
              type: 'warning'
            })
            // for (const item in this.userMenus) {
            //   if (this.userMenus[item].id === row.id) {
            //     this.userMenus.splice(item, 1)
            //   }
            // }
          } else {
            // 状态  1验证中 2有效 3无效
            this.emailAddress.push({ email: emailAddressTemp, state: 1 })
            this.emailAddressTemp = ''
            this.launchValidationResults([emailAddressTemp])
          }
        } else {
          this.$message({
            message: '邮箱地址不正确',
            type: 'warning'
          })
          return false
        }
      } else {
        this.$message({
          message: '不可为空',
          type: 'warning'
        })
        return false
      }
    },
    handleVerifyEmails() {
      console.log('开始批量验证')
      this.emailsAddressTemp = this.emailsAddress.trim()
      console.log(this.emailsAddressTemp, this.emailsAddressTemp.length)
      if (this.emailsAddressTemp.length !== 0) {
        let emailsAddressTempArray = this.emailsAddressTemp.split('\n').map(m => m.trim()).filter(m => m).filter(this.checkEmailAddress)
        // if (this.checkEmailAddress(emailAddressTemp)) {}
        if (emailsAddressTempArray.length > 0) {
          emailsAddressTempArray = this.$common.uniqueArray(emailsAddressTempArray).filter(m => !this.emailAddress.some(e => e.email === m))
          this.emailAddress.push(...emailsAddressTempArray.map(m => ({ email: m, state: 1 })))
          this.emailsAddressTemp = ''
          this.launchValidationResults(emailsAddressTempArray)
        } else {
          this.$message({
            message: '不可为空',
            type: 'warning'
          })
          return false
        }
      } else {
        this.$message({
          message: '不可为空',
          type: 'warning'
        })
        return false
      }
    },
    handleEmailRemove(val) {
      this.emailAddress.splice(this.emailAddress.findIndex(i => i === val), 1)
    },
    handleSaveToCustomer(val) {
      this.$message({
        message: '敬请期待...',
        type: 'warning'
      })
    },
    checkEmailAddress(szMail) {
      const szReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
      const bChk = szReg.test(szMail)
      console.log(bChk, '111')
      return bChk
    },
    async launchValidationResults(email) {
      console.info('准备验证邮件', email)

      if (this.validating || !email || email.length === 0) {
        return
      }
      this.validating = true
      let i
      let j
      let temp
      const chunk = 5
      for (i = 0, j = email.length; i < j; i += chunk) {
        temp = email.slice(i, i + chunk)
        try {
          await postLongTimeAction({ email: temp }, 'EmailVerify/Verify')
            .then(({ data }) => {
              for (const key in data) {
                const email = this.emailAddress.find(m => m.email === key)
                if (email) {
                  email.state = data[key] ? 2 : 3
                }
              }
              this.emailAddress = [...this.emailAddress]
            })
        } catch (e) {
          console.error(e)
          for (const key in temp) {
            const email = this.emailAddress.find(m => m.email === temp[key])
            if (email) {
              email.state = 3
            }
          }
          this.emailAddress = [...this.emailAddress]
        }
      }
      this.validating = false
    },
    creatEmailVerify(state, emailAddress) {
      postAction({ emailAddress: emailAddress, state: state ? 1 : 2, recentlyUpdatedWay: true }, 'EmailMarketing/CreatEmailVerify')
        .then((res) => {
          if (res.code === 20000) {
            console.log('保存到邮箱成功')
          } else {
            this.$message({
              message: '保存到数据库失败',
              type: 'warning'
            })
          }
        })
    },
    handleClickTab(tab, event) {
      if (tab.name === 'first-second') {
        this.getLogList()
      }
    },
    getLogList() {
      getAction(this.listQuery, 'emailVerify/Index').then((data) => {
        this.listQuery.total = data.data.total
        this.verifyLogData = data.data.items
      })
    },
    handleClose() {
      this.$emit('update:show', false)
    }
  }

}
</script>

<style scoped>
    .no-padding-input /deep/ .el-input__inner
    {
        padding:0px;
        border:unset;
    }
    .no-border-radius-input /deep/ .el-input__inner
    {
        border-radius: 0px 4px 4px 0;
        border-top-left-radius: 0px;
        border-bottom-left-radius: 0px;
    }
    .state_verification{
      color:orange
    }
    .state_valid{
      color:green;
    }
    .state_invalid{
      color:red;
    }
    .state_save{
      color:rgb(61, 47, 255);
    }
    .dialog-scrollbar {
      height: 820px;
    }
</style>
